﻿

using BasicFrameworkDemo.Model;
using BasicFrameworkDemo.OperationLog;


namespace BasicFrameworkDemo.Interceptor
{
    using System;

    using BasicFrameworkDemo.Utility;

    using Castle.DynamicProxy;


    public class CommonInterceptor : IInterceptor
    {
        private readonly IOperationLog operationLog;

        public CommonInterceptor(IOperationLog operationLog)
        {
            this.operationLog = operationLog;
        }

        public void Intercept(IInvocation invocation)
        {
            var errorCode = string.Empty;
            try
            {
                operationLog.WriteLog(invocation,OperationLogType.Request);
                invocation.Proceed();
            }
            catch (Exception exception)
            {
                exception.WriteLog();
                errorCode = "E003";
            }

            if (invocation.ReturnValue == null)
            {
                var result = (InterceptorCommon.GetConstructor(invocation.Method.ReturnType) as BaseResponse) ?? new BaseResponse();
                result.ErrorCode = errorCode;
                result.Status = 0;
                invocation.ReturnValue = result;
            }

            //InterceptorCommon.GetChildrenConstructor(invocation.ReturnValue);

            operationLog.WriteLog(invocation, OperationLogType.Response);
        }
    }
}
